import { Action, createSlice } from '@reduxjs/toolkit';
import axios from 'axios';
import { useDispatch, useSelector } from 'react-redux';
import undoable from 'redux-undo';
import * as api from '../../../api';

export const reducerName = 'dragger'

export const moduleSlice = createSlice({
  name: reducerName,
  initialState: {
    selectIndex: [] as number[],
    cards: [],
  },
  reducers: {
    setState: (state, { payload, type }) => {
      if (Object.keys(payload).includes('cards')) {
        localStorage.setItem('cards', JSON.stringify(payload.cards));
        api.edit({
          id:1,
          data: JSON.stringify(payload.cards),
        })
      }

      state = {
        ...state,
        ...payload,
      }
      // state赋值为新的对象后，需要return state来触发更新
      return state;
    },
  },
});

// 为每个 case reducer 函数生成 Action creators
export const { setState } = moduleSlice.actions;


export const useStateFromRedux = (key: string) => {
  const dispatch = useDispatch();
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  const state = useSelector((state: any) => state[reducerName].present[key]);
  const _setState = () => {
    // 需要通过闭包将上一次的state状态保存下来
    let newState = state;
    return (val: unknown) => {
      newState = typeof val === 'function' ?  val(newState) : val;
      dispatch(setState({
          [key]: newState
      }))
    }
  }
  return [state, _setState()]
}

export default undoable(moduleSlice.reducer, {
  filter: function filterActions(action: Action) {
    const payload = (action as unknown as Action & { payload: { cards?: unknown } }).payload;
    return Boolean(payload.cards)
  }
});